import { useStore } from 'vuex'
import { computed, ref } from 'vue'
import { ANY_ARRAY } from '@/type'
/**
 * 全局状态对象
 */
export const global: ANY_ARRAY = {}
export const useStoreRef = <T>(type: string) => {
  const store = useStore()
  const key = type.split('/')
  const state = computed(() => {
    let result = store.state[key[0]]
    for (let i = 1; i < key.length; i++) {
      result = result[key[i]]
    }
    return result as T
  })
  const commit = (value: T) => {
    store.commit(`${key.slice(0, key.length - 1).join('/')}/update`, value)
    return value
  }
  return [state, commit]
}
export function useRef <T> (value: T, key: string) {
  const newKey = key.toString()
  if (!global[newKey] && newKey) {
    global[newKey] = value
  }
  const reunst = ref(global[newKey])
  const update = (val: T) => {
    global[newKey] = val
    reunst.value = val
  }
  return [reunst, update]
}
